<template>
    <view class="container">
        <!-- 搜索区域开始 -->
        <TridentSearch placeholder="用户名/手机号" @search="handleSearch"/>
        <!-- 搜索区域结束 -->

        <!-- 搜索列表区域开始 -->
        <div class="list-wrap">
            <view v-for="(item, index) in userList" :key="index" @click="goto(item.url || '')">
                <TridentCellItem :item="item" v-if="item?.name"/>
            </view>
        </div>
        <!-- 搜索列表区域结束 -->
    </view>
</template>

<script setup lang="ts">
import { reqUserListAPI } from '@/apis/user'
import type { CellItem } from '@/types/global'
import type { SearchUserParams } from '@/types/user'
import { inject, reactive, ref } from 'vue'
import { goto } from '@/utils/tools'

// ----------------- 定义全局变量开始 -----------------
// 全局属性
const global:any = inject('global')

const keyword = ref<string>('')
// ----------------- 定义全局变量结束 -----------------



// ------------------- 搜索功能开始 -------------------
// 搜索参数
const params = reactive<SearchUserParams>({
    mobile: '',
    username: ''
})

// 用户列表
const userList = ref<CellItem[]>([])

// 搜索用户
const searchUser = async () => {
    params.mobile = ''
    params.username = ''
    if (keyword.value) {
        userList.value = []
        // 判断搜索关键字是手机号还是用户名
        const pattern = /^1[3|5|7|8|9]\d{9}$/
        if (pattern.test(keyword.value)) {
            params.mobile = keyword.value
        } else {
            params.username = keyword.value
        }

        const result = await reqUserListAPI(params)
        result.data.users.forEach((user) => {
            userList.value.push({
                name: user.username,
                image_url: user.avatar_url ? global.FILE_DOMAIN + user.avatar_url : '/static/images/default_avatar.png',
                url: '/pagesFriend/wait_add/index?uid='+user.uid
            })
        })
    }
}

// 处理搜索
const handleSearch = (value: any) => {
    keyword.value = value.keyword.value
    searchUser()
}
// ------------------- 搜索功能结束 -------------------
</script>

<style scoped lang="scss">
.container {}
</style>